package com.wxmit.module.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wxmit.module.system.domain.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangxiong
 * @date 2023/11/20 15:14
 */
@Service("TestDataDynamicService")
public class DataDynamicService {

    @Autowired
    public DataDynamicTransactionalService testDataDynamicTransactionalService;

    @DS("master")
    public void query01(){
        LambdaQueryChainWrapper<SysRole> lambdaQuery = Db.lambdaQuery(SysRole.class).select(SysRole::getRoleName).eq(SysRole::getId,6L);
        List<String> list = lambdaQuery.list().stream().map(SysRole::getRoleName).collect(Collectors.toList());
        System.out.println(list);
    }


    @DS("slave")
    public void query02(){
        LambdaQueryChainWrapper<SysRole> lambdaQuery = Db.lambdaQuery(SysRole.class).select(SysRole::getRoleName).eq(SysRole::getId,6L);
        List<String> list = lambdaQuery.list().stream().map(SysRole::getRoleName).collect(Collectors.toList());
        System.out.println(list);
    }

    /**
     *  测试多数据源事务
     *   ⚠️ 注意： 统一事务内 @Transactional 与 @DSTransactional 混用会导致多数据源事务失效！
     * @param isSuccess 事务是否成功
     * @throws RuntimeException 终止事务抛出的异常
     */
    @DSTransactional(rollbackFor = Exception.class)
    public void doTransactional(boolean isSuccess) throws RuntimeException{
        testDataDynamicTransactionalService.do01();
        query01();
        if(!isSuccess)
            throw new RuntimeException("终止事务");
        testDataDynamicTransactionalService.do02();
    }

}
